#! /usr/bin/env python

"""
Use the following in /etc/munin/plugin-conf.d/wormhole :

[wormhole_*]
env.serverdir /path/to/your/wormhole/server
"""

import os, sys, time, json

CONFIG = """\
graph_title Magic-Wormhole Server Errors
graph_vlabel Events Since Reboot
graph_category network
nameplates.label Nameplate Errors (total)
nameplates.draw LINE1
nameplates.type GAUGE
mailboxes.label Mailboxes (total)
mailboxes.draw LINE1
mailboxes.type GAUGE
mailboxes_scary.label Mailboxes (scary)
mailboxes_scary.draw LINE1
mailboxes_scary.type GAUGE
transit.label Transit
transit.draw LINE1
transit.type GAUGE
"""

if len(sys.argv) > 1 and sys.argv[1] == "config":
    print CONFIG.rstrip()
    sys.exit(0)

serverdir = os.environ["serverdir"]
fn = os.path.join(serverdir, "stats.json")
with open(fn) as f:
    data = json.load(f)
if time.time() > data["valid_until"]:
    sys.exit(1) # expired

r = data["rendezvous"]["since_reboot"]
print "nameplates.value", (r["nameplates_total"]
                           - r["nameplate_moods"].get("happy", 0))
print "mailboxes.value", (r["mailboxes_total"]
                          - r["mailbox_moods"].get("happy", 0))
print "mailboxes_scary.value", r["mailbox_moods"].get("scary", 0)
t = data["transit"]["since_reboot"]
print "transit.value", (t["total"] - t["moods"].get("happy", 0))
